<template> 
  <div class="app-container">
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>推荐分类列表</span>
      <el-tooltip class="item" effect="dark" content="目前小程序端最多显示10个分类" placement="top">
        <el-button size="medium" type="primary" class="btn-add" @click="handleAdd()">添加分类</el-button>
      </el-tooltip>
    </el-card>
    <div class="choose-dept">
      <el-tabs v-model="activeDept" @tab-click="deptChange">
        <el-tab-pane v-for="item in depotList" :label="item.name" :name="item.name" :id="item.id" :key="item.id"></el-tab-pane>
      </el-tabs>
    </div>
    <div class="table-container">
      <el-table ref="homeAdvertiseTable"
                :data="list"
                style="width: 100%;"
                @selection-change="handleSelectionChange"
                v-loading="listLoading" border>
        <!-- <el-table-column type="selection" width="60" align="center"></el-table-column> -->
        <el-table-column label="编号" width="100" align="center">
          <template slot-scope="scope">{{scope.row.id}}</template>
        </el-table-column>
        <el-table-column label="分类名称" width="350" align="center">
          <template slot-scope="scope">{{scope.row.showName}}</template>
        </el-table-column>
        <el-table-column label="图标" width="240" align="center">
          <template slot-scope="scope"><img style="max-width: 260px;max-height:100px;" :src="scope.row.icon"></template>
        </el-table-column>
        <el-table-column label="排序" width="120" align="center">
          <template slot-scope="scope">{{scope.row.sort}}</template>
        </el-table-column>
        <el-table-column label="操作"  align="center">
          <template slot-scope="scope">
            <el-button size="mini"
                       
                       @click="handleUpdate(scope.$index, scope.row)">编辑
            </el-button>
            <el-button size="mini"
                       type="danger"
                       @click="handleDelete(scope.$index, scope.row)">删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 新增分类的弹窗 -->
    <el-dialog title="新增分类" :visible.sync="isNewProCateOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="newForm" style="width:25rem;" :rules="newFormRules" ref="newForm">
            <el-form-item label="分类名称" prop="showName" required label-width="5rem">
                <el-input v-model="newForm.showName" placeholder="最多维护4个汉字" ></el-input>
            </el-form-item>
            <el-form-item label="图标"  prop="icon" label-width="5rem">
               <!-- <el-input v-model="editForm.icon" placeholder="" style="width:16.66rem;"></el-input> -->
                <single-upload v-model="newForm.icon" tip="请上传 96*96px 的图片"></single-upload>
            </el-form-item>
            <el-form-item label="商品分类：" prop="categoryId">
                <el-cascader
                v-model="newForm.categoryId"
                :options="productCateOptions">
                </el-cascader>
            </el-form-item>
            <el-form-item label="选择仓库" required prop="depotId">
                <el-select v-model="newForm.depotId">
                <el-option
                    v-for="dept in depotList"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id">
                </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="排序"  prop="sort" label-width="5rem">
                <el-input v-model="newForm.sort" placeholder="" ></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveNewProCate('newForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isNewProCateOpen = false">关闭</el-button>
        </div>
    </el-dialog>
    <!-- 编辑分类的弹窗 -->
    <el-dialog title="编辑分类" :visible.sync="isEditProCateOpen" :close-on-click-modal="false" :show-close="true" class="adjustmentBox">
        <el-form :model="editForm" style="width:25rem;" :rules="editFormRules" >
            <el-form-item label="分类名称" prop="showName" required label-width="5rem">
                <el-input v-model="editForm.showName" placeholder="最多维护4个汉字" ></el-input>
            </el-form-item>
            <el-form-item label="图标"  prop="icon" label-width="5rem">
                <!-- <el-input v-model="editForm.icon" placeholder="" style="width:16.66rem;"></el-input> -->
                <single-upload v-model="editForm.icon" tip="请上传 96*96px 的图片"></single-upload>
            </el-form-item>
            <el-form-item label="商品分类：" prop="categoryId">
                <el-cascader
                v-model="editForm.categoryId"
                :options="productCateOptions">
                </el-cascader>
            </el-form-item>
             <el-form-item label="选择仓库" required prop="depotId">
                <el-select v-model="editForm.depotId" @change="selectDepotChange">
                <el-option
                    v-for="dept in depotList"
                    :key="dept.id"
                    :label="dept.name"
                    :value="dept.id">
                </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="排序"  prop="sort" label-width="5rem">
                <el-input v-model="editForm.sort" placeholder="" ></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="saveProCateInfo('editForm')" style="color:#fff;background-color:#417FF6;">保存</el-button>
            <el-button @click="isEditProCateOpen = false">关闭</el-button>
        </div>
    </el-dialog>
  </div>
</template>
<script>
  import {
      fetchHomeProductCatrList,
      createHomeProductCate,
      updateHomeProductCate,
      deleteHomeProductCate
    } 
    from '@/api/home-productCate';
  import {fetchList as fetchDeptList} from '@/api/depository'
  import SingleUpload from '@/components/Upload/singleUpload'
  import {fetchListWithChildren} from '@/api/productCate'
  const defaultListQuery = {
   // pageNum: 1,
    //pageSize: 5,
    depotId:null,
    //name: null,
    //type: 1,
    //endTime:null
  };

  export default {
    name: 'homeAdvertiseList',
    components:{SingleUpload},
    data() {
      return {
        listQuery: Object.assign({}, defaultListQuery),
        list: null,
        total: null,
        listLoading: false,
        multipleSelection: [],
        operates: [
          {
            label: "删除",
            value: 0
          }
        ],
        productCateOptions:[],//产品分类
        depotList:[],//仓库列表
        activeDept:null,//选中的仓库name
        isNewProCateOpen:false,
        isEditProCateOpen: false,
        newForm:{
            showName:"",
            icon:"",
            categoryId:null,
            sort:null,
            depotId:null,
        },
        editForm:{
            showName:"",
            icon:"",
            categoryId:null,
            sort:null,
             depotId:null,
        },
        newFormRules:{
            showName:[
                { required: true,  message: '分类名不能为空', trigger: ['blur','change']}
             ],
            categoryId:[
                { required: true,  message: '分类不能为空', trigger: ['blur','change']}
             ],
             sort:[
                { required: false,  message: '排序不能为空', trigger: ['blur','change']}
             ],
             icon:[
                { required: true,  message: '图标不能为空', trigger: ['blur','change']}
             ],
            depotId:[
                {required:true, message:'请选择仓库',trigger:"blur"}
            ]
          },
          editFormRules:{
            showName:[
                { required: true,  message: '分类名不能为空', trigger: ['blur','change']}
             ],
             categoryId:[
                { required: true,  message: '分类不能为空', trigger: ['blur','change']}
             ],
             sort:[
                { required: false,  message: '排序不能为空', trigger: ['blur','change']}
             ],
             icon:[
                { required: true,  message: '图标不能为空', trigger: ['blur','change']}
             ],
             depotId:[
                {required:true, message:'请选择仓库',trigger:"blur"}
            ]
          },
      }
    },
    created() {
      this.getList();
      this.getProductCateList();
    },
    // filters:{
    //   formatType(type){
    //     if(type===1){
    //       return 'APP首页轮播';
    //     }else{
    //       return 'PC首页轮播';
    //     }
    //   },
    //   formatTime(time){
    //     if(time==null||time===''){
    //       return 'N/A';
    //     }
    //     let date = new Date(time);
    //     return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    //   },
    // },
    methods: {
      handleResetSearch() {
        this.listQuery = Object.assign({}, defaultListQuery);
      },
      handleSearchList() {
        this.listQuery.pageNum = 1;
        this.getList();
      },
      handleSelectionChange(val){
        this.multipleSelection = val;
      },
      handleSizeChange(val) {
        this.listQuery.pageNum = 1;
        this.listQuery.pageSize = val;
        this.getList();
      },
      handleCurrentChange(val) {
        this.listQuery.pageNum = val;
        this.getList();
      },
      saveNewProCate(formName){
        let self = this;
        //console.log(self.newForm);
        self.newForm.categoryId = self.newForm.categoryId.pop();
        //console.log(self.newForm);
        createHomeProductCate(self.newForm).then(res=>{
            if(res.code ==200){
              self.$message({
                type: 'success',
                message: '新建成功!'
              });
              self.isNewProCateOpen = false;
              self.$refs[formName].resetFields();
              self.newForm.categoryId = null;
              self.getList();
            }
        })
      },
      saveProCateInfo(){
          let self = this;
        console.log(self.editForm);
        if(self.editForm.categoryId.length ==2){
          self.editForm.categoryId = self.editForm.categoryId.pop();
        }
        console.log(self.editForm);
        updateHomeProductCate(self.editForm.currentId,self.editForm).then(res=>{
            if(res.code ==200){
              self.$message({
                type: 'success',
                message: '新建成功!'
              });
              self.isEditProCateOpen = false;
              self.getList();
            }
        })
      },
      handleUpdateStatus(index,row){
        this.$confirm('是否要修改上线/下线状态?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          updateStatus(row.id,{status:row.status}).then(response=>{
            this.getList();
            this.$message({
              type: 'success',
              message: '修改成功!'
            });
          });
        }).catch(() => {
          this.$message({
            type: 'success',
            message: '已取消操作!'
          });
          this.getList();
        });
      },
      handleDelete(index,row){
        this.deleteHomeAdvertise(row.id);
      },
      handleAdd(){
        //最大值经常变动，这里就不改了
        if(this.list.length < 12){
          this.newForm.categoryId = [];
          this.isNewProCateOpen =true;
        }else{
          this.$message({
            type:"info",
            message:"每个仓库最多维护12个产品分类"
          });
        }
      },
      selectDepotChange(newval){
          console.log(newval);
        this.editForm.depotId = newval;
        this.$forceUpdate();
      },
      handleUpdate(index,row){
       // this.$router.push({path: '/hds/updateAdvertise', query: {id: row.id}})
        this.isEditProCateOpen = true;
        this.editForm = Object.assign({},row);
        //console.log(this.activeDept);
        let depotName = this.activeDept;
        for(const depot of this.depotList){
            if(depot.name === depotName){
                this.editForm.depotId = depot.id;
                break
            }
        }
        //console.log(this.editForm.depotId);
        //this.editForm.depotId = JSON.parse(JSON.stringify(this.activeDept));
        this.editForm.id = row.id;
      },
      deptChange(tab, event){
        let self = this;
        let depotId = tab.$attrs.id;
        self.listQuery.depotId = depotId;
        fetchHomeProductCatrList(depotId).then(response => {
          this.listLoading = false;
          this.list = response.data;
          //this.total = response.data.total;
        })
      },
      getList() {
        let self = this;
        this.listLoading = true;
        fetchDeptList().then(({code,data})=>{
          if(code ==200 && data){
            this.depotList = data;
            for(const item of data){
              if(item.isDefault){
                self.activeDept= item.name;//页面一进来，首先选择显示默认仓库
                self.listQuery.depotId = item.id;
                break;
              }
            };
          }
          return data
        }).then(respon=>{
          fetchHomeProductCatrList(self.listQuery.depotId).then(response => {
            this.listLoading = false;
            this.list = response.data;
           // this.total = response.data.total;
          })
        });
        
      },
      getProductCateList() {
        fetchListWithChildren().then(response => {
          let list = response.data;
          this.productCateOptions = [];
          for (let i = 0; i < list.length; i++) {
            let children = [];
            if (list[i].children != null && list[i].children.length > 0) {
              for (let j = 0; j < list[i].children.length; j++) {
                children.push({label: list[i].children[j].name, value: list[i].children[j].id});
              }
            }
            this.productCateOptions.push({label: list[i].name, value: list[i].id, children: children});
          }
        });
      },
      deleteHomeAdvertise(ids){
        this.$confirm('是否要删除该广告?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
        //   let params=new URLSearchParams();
        //   params.append("ids",ids);
          deleteHomeProductCate(ids).then(response=>{
            this.getList();
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          });
        })
      }
    }
  }
</script>
<style scoped>
  .btn-add{
    margin-top: -8px;
  }
  .choose-dept >>> .el-tabs__item{
    font-size: 16px; 
  }
  .choose-dept >>> .el-tabs__header{
    margin: 15px 0 0;
  }
  .input-width {
    width: 203px;
  }
  /* 弹出框的宽度 */
.adjustmentBox >>> .el-dialog{
  width: 28rem;
} 
</style>


